layui.define(['table', 'form', 'helper', 'laydate'], function (exports) {
    var $         = layui.$
        , admin   = layui.admin
        , setter  = layui.setter
        , view    = layui.view
        , table   = layui.table
        , helper  = layui.helper
        , form    = layui.form;
    var baseTable = {
        config: {
            title          : ''
            , requestUrl   : ''
            , formTemplate : ''
            , tableElem    : '#layuiadmin-table'
            , tableName    : ''
            , tableCols    : []
            , areaWidth    : 450
            , areaHeight   : 350
            , batDelete    : false
            , search       : false
            , submitBtn    : 'layuiadmin-submit'
            , formRender   : 'layuiadmin-form'
            , tableWhere   : {}
            , getDialogInfo: null
            , tableEvent   : function (event, obj) {

            }
            , export       : false
            , tableOptions : {}
            , dateFilter   : false
            , dateItem     : ['today', 'yesterday', 'threeday', 'week', 'month']
            , dateTitle    : [
                {
                    key  : 'today',
                    id   : 1,
                    title: '今天',
                },
                {
                    key  : 'yesterday',
                    id   : 2,
                    title: '昨天',
                },
                {
                    key  : 'threeday',
                    id   : 3,
                    title: '近3天',
                },
                {
                    key  : 'week',
                    id   : 4,
                    title: '近7天',
                },
                {
                    key  : 'month',
                    id   : 5,
                    title: '近30天',
                }
            ]
            , dateMap      : {today: 1, yesterday: 2, threeday: 3, week: 4, month: 5}
        }
        , render(config) {
            if (!config.tableOptions) {
                config.tableOptions = {};
            } else {
                if (!config.tableOptions['totalRow']) {
                    config.tableOptions['totalRow'] = false;
                }
            }
            if (config.export === undefined) {
                config.export = false;
            }
            this.config = $.extend(this.config, config);
            let options = {
                elem            : this.config.tableElem
                , url           : setter.requestUrl + this.config.requestUrl //模拟接口
                , cols          : [
                    this.config.tableCols
                    ,]
                , page          : true
                , limit         : 10
                , limits        : [10, 15, 20, 25, 30]
                , text          : {
                    none: '暂无数据'
                }
                , where         : this.config.tableWhere
                , autoSort      : false
                , toolbar       : false
                , defaultToolbar: []
                , exportTitle   : '' // 导出时的标题
                , done : this.requestDone ,
            };
            if (this.config.tableOptions) {
                options = Object.assign(options, this.config.tableOptions);
            }
            if (this.config.export) {
                options.defaultToolbar.push({
                    title     : '导出'
                    , layEvent: 'EXPORT'
                    , icon    : 'layui-icon-export'
                });
            }
            table.render(options);
            this.parseEle();
            this.listen();
            this.search();
            this.helper();
        }
        /**
         * 请求完成后的回调
         * @param res
         */
        , requestDone(res){
            if (undefined !== res.pageInfo){
                let pageInfo = res.pageInfo;
                if (pageInfo.title) baseTable.config.title = pageInfo.title;
                let crumbs = pageInfo.crumbs;
                if (crumbs.length > 0) baseTable.renderCrumbs(crumbs);
            }
        }
        /**
         * 渲染面包屑
         * @param crumbs
         */
        , renderCrumbs(crumbs){
            let html = '<a lay-href="">主页</a>';
            crumbs.forEach((item) => {
                html += '<span lay-separator>/</span><a><cite>' + item + '</cite></a>';
            })
            $('.layui-breadcrumb').html(html);
        }
        , listen() {
            var self = this;
            //监听工具条
            table.on('tool(' + self.config.tableName + ')', function (obj, item) {
                var data = obj.data;
                if (obj.event === 'del') {
                    let title = '确定删除此' + self.config.title + '？' , postUrl = self.config.requestUrl + '/delete?id=' + obj.data.id;
                    helper.confirmReload(title , postUrl , obj.data.id , function(){
                        obj.del();
                    });
                } else if (obj.event === 'edit') {
                    admin.popup({
                        title    : '编辑' + self.config.title
                        , area   : [self.config.areaWidth + 'px', self.config.areaHeight + 'px']
                        , id     : 'LAY-popup-content-comm'
                        , success: function (layero, index) {
                            window.params = data;
                            view(this.id).render(self.config.formTemplate, data).done(function () {
                                self.helper();
                                form.render(null, self.config.formRender);
                                //监听提交
                                form.on('submit(' + self.config.submitBtn + ')', function (res) {
                                    var field = res.field; //获取提交的字段
                                    field.id  = data.id;
                                    helper.post(self.config.requestUrl + '/edit', field, function (res) {
                                        helper.success(res.msg, function () {
                                            layui.table.reload(self.config.tableName); //重载表格
                                            layer.close(index); //执行关闭 
                                        });
                                    })
                                });
                            });
                        }
                    });
                } else {
                    self.config.tableEvent(obj.event, obj);
                }
            });
            table.on('toolbar(' + self.config.tableName + ')', function (obj) {
                if (self.config.export && obj.event == 'EXPORT') {
                    helper.loading('请稍后...');
                    let param = $('.layui-form-item [name]').serialize() + '&export=1';
                    helper.get(self.config.requestUrl + '?' + param, function (res) {
                        let title = res.title;
                        if (res['title'] === undefined || title.length == 0) {
                            helper.error('无效的导出信息');
                            return;
                        }
                        let data = res.data;
                        table.exportFile(title, data, 'xls', self.config.exportTitle + (new Date()).getTime()); //默认导出 csv，也可以为：xls
                    })
                }
            })
            table.on('sort(' + self.config.tableName + ')', function (obj) {
                let where  = self.config.tableWhere
                where.sort = {
                    field: obj.field,
                    order: obj.type,
                };
                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                table.reload(self.config.tableName, {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                    , where : where
                });
            });
            var active = {
                add       : function () {
                    admin.popup({
                        title    : '添加' + self.config.title
                        , area   : [self.config.areaWidth + 'px', self.config.areaHeight + 'px']
                        , id     : 'LAY-popup-content-comm'
                        , success: function (layero, index) {
                            view(this.id).render(self.config.formTemplate).done(function () {
                                self.helper();
                                form.render(null, self.config.formRender);
                                //监听提交
                                form.on('submit(' + self.config.submitBtn + ')', function (data) {
                                    var field = data.field; //获取提交的字段
                                    helper.post(self.config.requestUrl + '/edit', field, function (res) {
                                        helper.success(res.msg, function () {
                                            layui.table.reload(self.config.tableName); //重载表格
                                            layer.close(index); //执行关闭 
                                        });
                                    })
                                });
                            });
                        }
                    });
                }
                , batchdel: function () {
                    if (!self.config.batDelete) {
                        return
                    }
                    var checkStatus = table.checkStatus(self.config.tableName)
                        , checkData = checkStatus.data; //得到选中的数据
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据');
                    }
                    layer.confirm('确定删除吗？', function (index) {
                        //执行 Ajax 后重载
                        /*
                        admin.req({
                        url: 'xxx'
                        //,……
                        });
                        */
                        table.reload(self.config.tableName);
                        layer.msg('已删除');
                    });
                }
            }
            $('.layui-btn.layuiadmin-btn').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
            form.on('switch(status)', function (data) {
                var id     = parseInt(data.value);
                var status = parseInt(this.checked ? '1' : '0');
                helper.loading('正在切换中...');
                var data = {
                    id      : id
                    , status: status
                    , field : data.elem.name
                };
                helper.post(self.config.requestUrl + '/status', data, function (res) {
                    helper.success(res.msg);
                })
            })
        }
        , search() {
            var self = this;
            if (!self.config.search) {
                return;
            }
            form.render(null, 'layuiadmin-search-form');
            //监听搜索
            form.on('submit(layuiadmin-search-form-btn)', function (data) {
                var field = data.field;
                //执行重载
                table.reload(self.config.tableName, {
                    where: field
                });
            });
        }
        , helper() {
            $('select[data-value]').each(function (index, item) {
                var value = $(item).attr('data-value');
                $(this).val(value);
            })
            if (this.config.dateFilter) {
                this.helperForDate();
            }
        }
        , helperForDate() {
            let filter = $('.date-filter');
            let html   = '<div class="layui-inline"><label class="layui-form-label">数据时间</label><div class="layui-input-inline" style="width: 300px;"><input type="text" readonly name="time" placeholder="请选择数据时间" autocomplete="off" class="layui-input layui-date"></div></div><div class="layui-inline"><div class="layui-btn-group times">';
            this.config.dateItem.forEach((item) => {
                if (this.config.dateMap[item]) {
                    let key       = this.config.dateMap[item];
                    let itemTitle = this.config.dateTitle[key - 1];
                    html += '<button type="button" class="layui-btn layui-btn-primary" data-type="' + key + '">' + itemTitle['title'] + '</button>';
                }
            })
            filter.prepend(html)
            $('.layui-date').each((index, item) => {
                layui.laydate.render({
                    elem : $(item)[0],
                    type : 'datetime',
                    range: '~',
                    done : (value, date, endDate) => {
                        this.config.tableWhere.time = value;
                    }
                })
            })
            let self = this;
            $('.times button').on('click', function (e) {
                let type               = parseInt(e.currentTarget.dataset.type);
                let dates              = new Date();
                let startTime, endTime = helper.getFullDate(new Date()) + ' 23:59:59';
                $($(this).siblings()).removeClass('layui-btn-success').addClass('layui-btn-primary')
                $(this).removeClass('layui-btn-primary').addClass('layui-btn-success');
                switch (type) {
                    case 1 :
                        // 今天

                        break;
                    case 2 :
                        // 昨天
                        dates.setDate(dates.getDate() - 1);
                        endTime = helper.getFullDate(dates) + ' 23:59:59';
                        break;
                    case 3 :
                        // 近三天
                        dates.setDate(dates.getDate() - 2);
                        break;
                    case 4 :
                        // 近一周
                        dates.setDate(dates.getDate() - 6);
                        break;
                    case 5 :
                        // 近一月
                        dates.setDate(dates.getDate() - 29);
                        break;
                }
                startTime = helper.getFullDate(dates) + ' 00:00:00';
                $('.layui-date').val(startTime + ' ~ ' + endTime);
                self.config.tableWhere.time = startTime + ' ~ ' + endTime;
            })
        }
        , parseEle() {
            var tableItem = this.config.tableElem
            if (tableItem) {
                this.config.tableName = tableItem.substr(1, tableItem.length)
            }
        }
    }
    exports('baseTable', baseTable)
})